package server.session;

import com.alibaba.fastjson.JSONObject;
import common.EnvelopeMessage;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class SessionManager {
    private static final DateTimeFormatter TIME_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final ConcurrentHashMap<Integer, Session> userSessions = new ConcurrentHashMap<>();//线程安全

    public static void bind(Integer userId, Session session) {
        userSessions.put(userId, session);
    }

    public static Session getSession(Integer userId) {
        return userSessions.get(userId);
    }

    public static void remove(Integer userId) {
        userSessions.remove(userId);
    }

    public static Map<Integer, Session> getAll() {
        return userSessions;
    }

    public static List<OnlineUser> listOnlineUsers() {
        return userSessions.values().stream().map(session -> {
            OnlineUser user = new OnlineUser();
            try {
                user.setClientId(session.getClientId());
                user.setUsername(session.getClientName());

                if (session.getChannel() != null && session.getChannel().getRemoteAddress() != null) {
                    user.setIp(session.getChannel().getRemoteAddress().toString());
                } else {
                    user.setIp("未知IP");
                }

                long lastActive = session.getLastActiveTime();
                if (lastActive > 0) {
                    LocalDateTime dateTime = LocalDateTime.ofInstant(
                            Instant.ofEpochMilli(lastActive),
                            ZoneId.systemDefault()
                    );
                    user.setLastActiveTime(TIME_FORMATTER.format(dateTime));
                } else {
                    user.setLastActiveTime("未知时间");
                }
            } catch (Exception e) {
                user.setIp("异常");
                user.setLastActiveTime("异常");
            }
            return user;
        }).collect(Collectors.toList());
    }

    public static boolean kickUser(Integer userId) {
        Session session = userSessions.get(userId);
        if (session != null) {
            try {
                EnvelopeMessage msg = new EnvelopeMessage("system", "kickOut", null);
                String json = JSONObject.toJSONString(msg);
                session.send(json);

                session.getChannel().close();
                userSessions.remove(userId);
                System.out.println("用户 " + userId + " 被踢下线");

                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }


    public static boolean toggleMuteUser(Integer userId) {

        return false;
    }
}


